@echo off
setlocal enabledelayedexpansion
chcp 65001 > nul

:: =================================================================
:: Weiyun Temporary Files Cleaner
:: Description: Cleans temporary files and directories created by Weiyun
:: =================================================================

echo Weiyun Temporary Files Cleaner
echo ============================
echo.

:: Clean weiyun_* directories and files in temp folder
choice /C YN /M "Clean all weiyun_* temporary files? (Y=Yes, N=No)"
if not errorlevel 2 (
    echo [INFO] Cleaning weiyun_* directories and files...
    set "cleaned_count=0"
    for /d %%d in ("%temp%\weiyun_*") do (
        echo [INFO] Removing directory: %%d
        rd /s /q "%%d" 2>nul
        if !errorlevel! equ 0 (
            set /a cleaned_count+=1
            echo [SUCCESS] Directory removed successfully
        ) else (
            echo [WARNING] Failed to remove directory: %%d
        )
    )
    echo [INFO] Cleaned !cleaned_count! temporary directories
)

:: Clean main script files
choice /C YN /M "Delete main script files? (Y=Yes, N=No)"
if not errorlevel 2 (
    echo [INFO] Cleaning main script files...
    set "deleted_count=0"
    for %%f in (
        "weiyun_downloader.cmd"
        "weiyun_downloader_win7.cmd"
        "weiyun_3.9.0_downloader_win7.cmd"
    ) do (
        if exist "%%f" (
            echo [INFO] Deleting file: %%f
            del /f /q "%%f" 2>nul
            if !errorlevel! equ 0 (
                set /a deleted_count+=1
                echo [SUCCESS] File deleted successfully
            ) else (
                echo [WARNING] Failed to delete file: %%f
            )
        ) else (
            echo [INFO] File not found: %%f
        )
    )
    echo [INFO] Deleted !deleted_count! script files
    
    :: Create self-destruct script
    set "self_destruct=%temp%\cleanup_self_destruct_%random%.cmd"
    (
        echo @echo off
        echo timeout /t 3 /nobreak ^> nul
        echo del /f /q "%~f0"
        echo del /f /q "!self_destruct!"
    ) > "!self_destruct!"
    
    if exist "!self_destruct!" (
        echo [INFO] Cleanup complete. This script will self-destruct in 3 seconds...
        start /b "" cmd /c "!self_destruct!"
        exit /b 0
    ) else (
        echo [ERROR] Failed to create self-destruct script
        echo [INFO] Please manually delete this script if needed
        pause
        exit /b 1
    )
)

echo [INFO] Cleanup complete.
pause
exit /b 0
